package cn.likun.kit;

import java.util.HashMap;
import java.util.Map;

import cn.likun.kit.validate.ValidateCommons;

/**
 *<p>重试(当发生异常)执行指定方法</p>
 */
public abstract class Retry {

	private Map<String,Object> param;
	private int time = 10;
	private int interval = 10;
	
	public Retry(Map<String,Object> param) {
		this(param, 10, 10);
	}
	
	/**
	 * @param param 参数
	 * @param time 重试次数,默认10次
	 * @param interval 重试间隔(秒),默认10秒
	 */
	public Retry(Map<String,Object> param , int time, int interval) {
		if (ValidateCommons.isEmpty(param)) {
			param = new HashMap<String, Object>();
		}
		this.param = param;
		this.time = time;
		this.interval = interval;
	}
	
	protected abstract Object getObject(Map<String,Object> param) throws Exception;
	
	public Object doRetry() throws Exception {
		Object obj = null;
		for (int i = 1 ; i <= time; i++) {
			try {
				obj = getObject(param);
				break;
			} catch (Exception e) {
				if (i == time) {
					Logger.error(getClass(), new StringBuffer().append("系统已执行").append(time).append("   次获取对象，获取对象失败：").toString(),e);
					throw new Exception(e);
				} else {
					Logger.warn(getClass(), new StringBuffer().append("第 ").append(i).append(" 次获取对象失败，系统将在 ").append(interval).append(" 秒后再次执行").toString(), e);
					Thread.sleep(1000 * interval);
				}
			}
		}
		return obj;
	}
	
}
